"""
演示页面，展示组件库的各种组件和功能
"""
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QLabel, QTabWidget, QScrollArea, QGridLayout, QGroupBox)
from PyQt5.QtCore import Qt, QSize
from component.button import Button
from component.table import Table
from component.message import Message, MessageBox, Notification
from component.theme import Theme


class Demo(QMainWindow):
    """演示页面，展示组件库的各种组件和功能"""
    
    def __init__(self, app=None):
        super().__init__()
        
        print("初始化Demo窗口...")
        self.setWindowTitle("PyQt Element Plus 风格组件库演示")
        self.resize(800, 600)
        
        # 确保窗口居中显示
        self.setGeometry(100, 100, 800, 600)
        
        # 应用主题
        if app:
            print("应用主题到应用...")
            Theme.apply_theme(app)
        else:
            # 如果没有传入app，则应用到当前窗口
            from PyQt5.QtWidgets import QApplication
            print("应用主题到当前实例...")
            Theme.apply_theme(QApplication.instance())
        
        # 创建中央部件
        print("创建中央部件...")
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建标题
        print("创建标题...")
        title = QLabel("PyQt Element Plus 风格组件库演示")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet(f"""
            font-size: {Theme.FONT_SIZE_EXTRA_LARGE}px;
            font-weight: bold;
            color: {Theme.TEXT_PRIMARY};
            margin: 20px 0;
        """)
        main_layout.addWidget(title)
        
        # 创建标签页
        print("创建标签页...")
        tab_widget = QTabWidget()
        tab_widget.setStyleSheet(f"""
            QTabWidget::pane {{
                border: 1px solid {Theme.BORDER_LIGHT};
                border-radius: {Theme.BORDER_RADIUS_BASE}px;
                background-color: {Theme.BG_COLOR};
            }}
            
            QTabBar::tab {{
                padding: 8px 16px;
                margin-right: 4px;
                border: 1px solid {Theme.BORDER_LIGHT};
                border-bottom: none;
                border-top-left-radius: {Theme.BORDER_RADIUS_BASE}px;
                border-top-right-radius: {Theme.BORDER_RADIUS_BASE}px;
                background-color: {Theme.BG_COLOR_PAGE};
                color: {Theme.TEXT_REGULAR};
            }}
            
            QTabBar::tab:selected {{
                background-color: {Theme.BG_COLOR};
                color: {Theme.PRIMARY};
                border-bottom: 2px solid {Theme.PRIMARY};
            }}
            
            QTabBar::tab:hover:!selected {{
                background-color: {Theme.PRIMARY_LIGHTER};
            }}
        """)
        main_layout.addWidget(tab_widget)
        
        # 创建按钮演示页
        print("创建按钮演示页...")
        button_tab = self._create_button_demo()
        tab_widget.addTab(button_tab, "按钮")
        
        # 创建表格演示页
        print("创建表格演示页...")
        table_tab = self._create_table_demo()
        tab_widget.addTab(table_tab, "表格")
        
        # 创建消息演示页
        print("创建消息演示页...")
        message_tab = self._create_message_demo()
        tab_widget.addTab(message_tab, "消息通知")
        
        print("Demo窗口初始化完成")
    
    def _create_button_demo(self):
        """创建按钮演示页"""
        try:
            print("开始创建按钮演示页...")
            scroll = QScrollArea()
            scroll.setWidgetResizable(True)
            
            content = QWidget()
            layout = QVBoxLayout(content)
            layout.setSpacing(20)
            
            # 基础按钮
            print("创建基础按钮...")
            group_box = QGroupBox("基础按钮")
            group_layout = QHBoxLayout()
            group_layout.setSpacing(10)
            
            types = ["primary", "success", "warning", "danger", "info"]
            for type in types:
                button = Button(type.capitalize(), self, button_type=type)
                button.clicked.connect(lambda checked, t=type: Message.info(self, f"点击了{t}按钮"))
                group_layout.addWidget(button)
            
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 朴素按钮
            print("创建朴素按钮...")
            group_box = QGroupBox("朴素按钮")
            group_layout = QHBoxLayout()
            group_layout.setSpacing(10)
            
            for type in types:
                button = Button(type.capitalize(), self, button_type=type, plain=True)
                button.clicked.connect(lambda checked, t=type: Message.info(self, f"点击了朴素{t}按钮"))
                group_layout.addWidget(button)
            
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 圆角按钮
            print("创建圆角按钮...")
            group_box = QGroupBox("圆角按钮")
            group_layout = QHBoxLayout()
            group_layout.setSpacing(10)
            
            for type in types:
                button = Button(type.capitalize(), self, button_type=type, round=True)
                button.clicked.connect(lambda checked, t=type: Message.info(self, f"点击了圆角{t}按钮"))
                group_layout.addWidget(button)
            
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 不同尺寸
            print("创建不同尺寸按钮...")
            group_box = QGroupBox("不同尺寸")
            group_layout = QHBoxLayout()
            group_layout.setSpacing(10)
            
            sizes = ["large", "default", "small", "mini"]
            for size in sizes:
                button = Button(size.capitalize(), self, size=size)
                button.clicked.connect(lambda checked, s=size: Message.info(self, f"点击了{s}尺寸按钮"))
                group_layout.addWidget(button)
            
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 禁用状态
            print("创建禁用状态按钮...")
            group_box = QGroupBox("禁用状态")
            group_layout = QHBoxLayout()
            group_layout.setSpacing(10)
            
            for type in types:
                button = Button(type.capitalize(), self, button_type=type)
                button.setEnabled(False)
                group_layout.addWidget(button)
            
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            scroll.setWidget(content)
            print("按钮演示页创建完成")
            return scroll
        except Exception as e:
            print(f"创建按钮演示页时出错: {e}")
            # 返回一个空的部件，避免程序崩溃
            empty_widget = QWidget()
            empty_layout = QVBoxLayout(empty_widget)
            error_label = QLabel(f"创建按钮演示页时出错: {e}")
            error_label.setStyleSheet("color: red;")
            empty_layout.addWidget(error_label)
            return empty_widget
    
    def _create_table_demo(self):
        """创建表格演示页"""
        try:
            print("开始创建表格演示页...")
            scroll = QScrollArea()
            scroll.setWidgetResizable(True)
            
            content = QWidget()
            layout = QVBoxLayout(content)
            layout.setSpacing(20)
            
            # 基础表格
            print("创建基础表格...")
            group_box = QGroupBox("基础表格")
            group_layout = QVBoxLayout()
            
            headers = ["日期", "姓名", "地址"]
            data = [
                ["2023-01-01", "张三", "北京市朝阳区"],
                ["2023-01-02", "李四", "上海市浦东新区"],
                ["2023-01-03", "王五", "广州市天河区"],
                ["2023-01-04", "赵六", "深圳市南山区"],
                ["2023-01-05", "钱七", "杭州市西湖区"]
            ]
            
            table = Table(self, data, headers)
            table.setMinimumHeight(200)
            
            # 添加操作按钮
            button_layout = QHBoxLayout()
            
            add_button = Button("添加行", self, button_type="primary")
            add_button.clicked.connect(lambda: self._add_table_row(table))
            button_layout.addWidget(add_button)
            
            remove_button = Button("删除选中行", self, button_type="danger")
            remove_button.clicked.connect(lambda: self._remove_table_row(table))
            button_layout.addWidget(remove_button)
            
            clear_button = Button("清空表格", self, button_type="warning")
            clear_button.clicked.connect(lambda: table.clear())
            button_layout.addWidget(clear_button)
            
            group_layout.addWidget(table)
            group_layout.addLayout(button_layout)
            
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 带斑马纹表格
            print("创建带斑马纹表格...")
            group_box = QGroupBox("带斑马纹表格")
            group_layout = QVBoxLayout()
            
            table = Table(self, data, headers, stripe=True)
            table.setMinimumHeight(200)
            
            group_layout.addWidget(table)
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            scroll.setWidget(content)
            print("表格演示页创建完成")
            return scroll
        except Exception as e:
            print(f"创建表格演示页时出错: {e}")
            # 返回一个空的部件，避免程序崩溃
            empty_widget = QWidget()
            empty_layout = QVBoxLayout(empty_widget)
            error_label = QLabel(f"创建表格演示页时出错: {e}")
            error_label.setStyleSheet("color: red;")
            empty_layout.addWidget(error_label)
            return empty_widget
    
    def _add_table_row(self, table):
        """添加表格行"""
        table.add_row(["2023-01-06", "新用户", "新地址"])
        Message.success(self, "添加行成功")
    
    def _remove_table_row(self, table):
        """删除表格行"""
        selected_row = table.get_selected_row()
        if selected_row >= 0:
            table.remove_row(selected_row)
            Message.success(self, "删除行成功")
        else:
            Message.warning(self, "请先选择一行")
    
    def _create_message_demo(self):
        """创建消息演示页"""
        try:
            print("开始创建消息演示页...")
            scroll = QScrollArea()
            scroll.setWidgetResizable(True)
            
            content = QWidget()
            layout = QVBoxLayout(content)
            layout.setSpacing(20)
            
            # 消息提示
            print("创建消息提示部分...")
            group_box = QGroupBox("消息提示")
            group_layout = QVBoxLayout()
            
            message_layout = QHBoxLayout()
            message_layout.setSpacing(10)
            
            types = [
                ("info", "信息"),
                ("success", "成功"),
                ("warning", "警告"),
                ("error", "错误")
            ]
            
            for type, text in types:
                button = Button(f"{text}提示", self, button_type=type)
                button.clicked.connect(lambda checked, t=type, txt=text: self._show_message(t, txt))
                message_layout.addWidget(button)
            
            group_layout.addLayout(message_layout)
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 侧边通知
            print("创建侧边通知部分...")
            group_box = QGroupBox("侧边通知")
            group_layout = QVBoxLayout()
            
            notification_layout = QHBoxLayout()
            notification_layout.setSpacing(10)
            
            for type, text in types:
                button = Button(f"{text}通知", self, button_type=type)
                button.clicked.connect(lambda checked, t=type, txt=text: self._show_notification(t, txt))
                notification_layout.addWidget(button)
            
            group_layout.addLayout(notification_layout)
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            # 消息对话框
            print("创建消息对话框部分...")
            group_box = QGroupBox("消息对话框")
            group_layout = QVBoxLayout()
            
            message_box_layout = QHBoxLayout()
            message_box_layout.setSpacing(10)
            
            button = Button("确认对话框", self, button_type="primary")
            button.clicked.connect(self._show_confirm)
            message_box_layout.addWidget(button)
            
            button = Button("提示对话框", self, button_type="info")
            button.clicked.connect(self._show_alert)
            message_box_layout.addWidget(button)
            
            for type, text in types:
                button = Button(f"{text}对话框", self, button_type=type)
                button.clicked.connect(lambda checked, t=type, txt=text: self._show_message_box(t, txt))
                message_box_layout.addWidget(button)
            
            group_layout.addLayout(message_box_layout)
            group_box.setLayout(group_layout)
            layout.addWidget(group_box)
            
            scroll.setWidget(content)
            print("消息演示页创建完成")
            return scroll
        except Exception as e:
            print(f"创建消息演示页时出错: {e}")
            # 返回一个空的部件，避免程序崩溃
            empty_widget = QWidget()
            empty_layout = QVBoxLayout(empty_widget)
            error_label = QLabel(f"创建消息演示页时出错: {e}")
            error_label.setStyleSheet("color: red;")
            empty_layout.addWidget(error_label)
            return empty_widget
    
    def _show_message(self, type, text):
        """显示消息提示"""
        message = f"这是一条{text}消息"
        if type == "info":
            Message.info(self, message)
        elif type == "success":
            Message.success(self, message)
        elif type == "warning":
            Message.warning(self, message)
        elif type == "error":
            Message.error(self, message)
    
    def _show_notification(self, type, text):
        """显示侧边通知"""
        title = f"{text}通知"
        message = f"这是一条{text}通知消息，将在右侧显示并自动关闭"
        if type == "info":
            Notification.info(self, title, message)
        elif type == "success":
            Notification.success(self, title, message)
        elif type == "warning":
            Notification.warning(self, title, message)
        elif type == "error":
            Notification.error(self, title, message)
    
    def _show_confirm(self):
        """显示确认对话框"""
        result = MessageBox.confirm(self, "确认", "确定要执行此操作吗？")
        if result:
            Message.success(self, "您点击了确认按钮")
        else:
            Message.info(self, "您点击了取消按钮")
    
    def _show_alert(self):
        """显示提示对话框"""
        MessageBox.alert(self, "提示", "操作已完成")
    
    def _show_message_box(self, type, text):
        """显示消息对话框"""
        message = f"这是一个{text}对话框"
        if type == "info":
            MessageBox.info(self, text, message)
        elif type == "success":
            MessageBox.success(self, text, message)
        elif type == "warning":
            MessageBox.warning(self, text, message)
        elif type == "error":
            MessageBox.error(self, text, message) 